<script setup lang="ts">
import { ref } from 'vue';
import * as Y from 'yjs'

/**
 * 延迟函数
 * @param {number} ms
 * @returns
 */

const delay = (ms: number) =>
    new Promise((resolve) => {
        setTimeout(() => {
            resolve(ms);
        }, ms);
    });

let content = ref("");

const doc = new Y.Doc()
const text = doc.getText("doc1");
const manager = new Y.UndoManager(text);

const run = async () => {
    text.insert(0, "hello");
    content.value = text.toString();
    await delay(1000);

    text.insert(5, '-');
    content.value = text.toString();
    await delay(1000);

    text.insert(6, 'w');
    content.value = text.toString();
    await delay(1000);

    text.insert(7, 'x');
    content.value = text.toString();
    await delay(1000);

    manager.undo();
    content.value = text.toString();
    await delay(1000);

    manager.undo();
    content.value = text.toString();
    await delay(1000);

    text.insert(6, 'world');
    content.value = text.toString();
    await delay(1000);

    text.delete(5, 1);
    text.insert(5, ' ');
    content.value = text.toString();
    await delay(1000);
}

run();

let isShow = ref(false);

</script>

<template>
    <div class="hide"><input type="button" :value="`${isShow ? 'hide' : 'show'} yjs 1`" @click="isShow = !isShow"></div>
    <div v-if="isShow">
        <div class="desc">Y JS 示例 ：Y.Doc的使用</div>
        <div>content: <span class="content">{{ content }}</span></div>
    </div>
</template>

<style scoped>
.content {
    border: 1px solid orange;
}
</style>